<template>
  <div class="viewFunnelBox" :style="{ padding: '5px 0' }" v-if="arrSetting.length > 0">

    <!-- 【且】【或】切换 -->
<!--    <div class="andOrNotBox" v-if="arrSetting.length > 1"-->
<!--         @click="switchRelation">{{ relation.name }}</div>-->
		<div class="andOrNotBox-and" v-if="arrSetting.length > 1" :style="{color:this.relation.key==='and'?'#FFF':'rgba(0,0,0,.65)','background-color':this.relation.key==='and'? '#40a9ff':'#FFF'}"
				 @click="switchRelation">且</div>

		<div class="andOrNotBox-or" v-if="arrSetting.length > 1" :style="{color:this.relation.key==='or'?'#FFF':'rgba(0,0,0,.65)','background-color':this.relation.key==='or'? '#40a9ff':'#FFF'}"
				 @click="switchRelation">或</div>
    <!-- 动态添加自定义筛选项 start -->
    <div class="funnelSettingBox" v-for="(item, i) in arrSetting" :key="item.listKey+'_'">

      <!-- 1. 一级（主）下拉选项 start -->
      <a-select  @change="settingChange(i)"
								 placeholder="请选择"
								 class="a-select-width"
								 v-model="arrSettingName[i]"
								 show-search
                 >
        <a-select-option v-for="(cItem) in levelOneOpts"
                   :key="cItem.attrName" :value="cItem.attrName"
                   :style="{ 'max-width': '600px' }">
					{{cItem.attrName}}
				</a-select-option>
      </a-select>
      <!-- 1. 一级（主）下拉选项 end -->



      <!-- 2. 二级下拉选项，根据（一级）不同的 data_type 显示不同的下拉选项 start -->
      <a-select  :style="{ width: '150px' }"
								 v-if="arrSetting[i] && arrSetting[i].compareList!==undefined"
                 v-model="arrSettingCompare[i]" @change="changeSettingCompare(arrSettingCompare[i],i)">
        <a-select-option v-for="cItem in arrSetting[i].compareList"
                   :key="cItem.functionCode" :value="cItem.functionCode" >{{cItem.functionAlias}}</a-select-option>
      </a-select>
      <!-- 2. 二级下拉选项，根据（一级）不同的 data_type 显示不同的下拉选项 end -->

			<!-- 1.绝对时间 -->
			<template v-if="arrSettingCompare[i]==='absoluteBetween'">
				<a-form-model-item label="" :style="{ width: '250px' }">
					<a-range-picker class="date-range-leng" v-model="arrSettingValue[i]" :disabled-date="disabledDate" showTime/>
					<a-button icon="close-circle" type="link" @click="editCond(i)"/>
				</a-form-model-item>
			</template>

			<template v-else-if="arrSettingCompare[i]==='extractBetween'">
				<a-form-model-item label="">
					<span class="lianzi">在</span>
					<a-input
						@change="changeData"
						v-model="arrSettingValue[i][0]"
						class="input-leng-s"
					/>
					<span class="lianzi">到</span>
					<a-input
						@change="changeData"
						v-model="arrSettingValue[i][1]"
						class="input-leng-s"
					/>
					<span class="lianzi">之间</span>
					<!-- 移除筛选项 -->
					<a-button icon="close-circle" type="link" @click="editCond(i)"/>
				</a-form-model-item>
			</template>

			<template v-else-if="arrSettingCompare[i]==='relativeCurTime'">
				<a-form-model-item label="">
					<span class="lianzi">在</span>
					<a-input
						@change="changeData"
						v-model="arrSettingValue[i][0]"
						class="input-leng-s"
					/>
					<span class="lianzi">天</span>
					<a-select
						@change="changeData"
						v-model="arrSettingValue[i][1]"
						placeholder="请选择"
						class="select-leng-s"
					>
						<a-select-option value="before" key="before" label="aftbeforeer">之前</a-select-option>
						<a-select-option value="after" key="after" label="after">之内</a-select-option>
					</a-select>
					<a-button icon="close-circle" type="link" @click="editCond(i)"/>
				</a-form-model-item>
			</template>

			<template v-else-if="arrSettingCompare[i]==='relativeBetween'">
				<a-form-model-item label="">
					<span class="lianzi">在过去</span>
					<a-input
						@change="changeData"
						v-model="arrSettingValue[i][0]"
						class="input-leng-s"
					/>
					<span class="lianzi">天 到过去</span>
					<a-input
						@change="changeData"
						v-model="arrSettingValue[i][1]"
						class="input-leng-s"
					/>
					<span class="lianzi">天之内</span>
					<a-button icon="close-circle" type="link" @click="editCond(i)"/>
				</a-form-model-item>
			</template>

			<template v-else-if="arrSettingCompare[i]==='relativeEventTime'">
				<a-form-model-item label="">
					<span class="lianzi">在</span>
					<a-select
						@change="changeData"
						v-model="arrSettingValue[i][0]"
						placeholder="请选择"
						class="select-leng-s"
					>
						<a-select-option
							:value="flow.val"
							v-for="flow in timeFlow"
							:key="flow.val"
							:label="flow.label"
						>
							{{ flow.label }}
						</a-select-option>
					</a-select>
					<a-input
						@change="changeData"
						v-model="arrSettingValue[i][1]"
						class="input-leng-s"
					/>
					<a-select
						@change="changeData"
						v-model="arrSettingValue[i][2]"
						placeholder="请选择"
						class="select-leng-s"
					>
						<a-select-option
							:value="unit.key"
							v-for="unit in timeUnit"
							:key="unit.key"
							:label="unit.name"
						>
							{{ unit.name }}
						</a-select-option>
					</a-select>
					<span class="lianzi">之内</span>
					<a-button icon="close-circle" type="link" @click="editCond(i)"/>
				</a-form-model-item>
			</template>

			<template v-else-if="['isSet', 'notSet' ,'notEmpty' ,'isEmpty'].indexOf(arrSettingCompare[i]) > -1">
				<a-button icon="close-circle" type="link" @click="editCond(i)"/>
			</template>


			<template v-else-if="['notRegexp', 'regexp'].indexOf(arrSettingCompare[i]) > -1">
				<a-input v-model="arrSettingValue[i][0]" :style="{ width: '250px' }" @change="$forceUpdate()"></a-input>
				<a-button icon="close-circle" type="link" @click="editCond(i)"/>
			</template>

			<template v-else>
				<!-- 3.1 可输入多个值（数字或字符串）end -->
				<a-select placeholder="输入内容后，按回车可添加多个"
									v-if="arrSetting[i] && arrSetting[i].valueList!==undefined"
									v-model="arrSettingValue[i]" :style="{ width: '250px' }"
									mode="tags"
									@change="$forceUpdate()">
					<a-select-option v-for="(cItem,indValue) in arrSetting[i].valueList"
													 :key="indValue" :value="cItem" >{{cItem}}</a-select-option>
					<!--				<a-select-option v-for="(cItem, ind) in lastOptsMap[i][item.attrCode]"-->
					<!--									 :key="ind" :value="cItem" :label="cItem"></a-select-option>-->
				</a-select>
				<!-- 移除筛选项 -->
				<a-icon type="close" @click="editCond(i)" style="font-size: 16px;margin-left: 8px;color: #9AA2B4"/>
			</template>





    </div>
    <!-- 动态添加自定义筛选项 end -->

  </div>
</template>


<script>
  /* dataType 类型配置 */
  import DataTypeConfig from './dataType.config'

  /**
   * api 接口
   * */
  import { valueList ,userAttrList,compareList} from '../../../../api/userAttr'
	import moment, { Moment } from 'moment'


  export default {
    name: 'custom-screen',

    props: {
      /**
       * 判断是否是事件属性 默认为是
       * */
      isEvent:{
        type: Boolean,
        default:()=>{return true}
      },
      /**
       * 是否有父级（默认无，可直接调用全部接口）
       * 如果有，则需要传下面的 supName 参数才能调用接口
       * */
      isSupName: {
        type: Boolean,
        default: () => { return false }
      },

      /**
       * 上级 name，如：'$AppClick'
       * 用于创建/编辑漏斗时，根据上级 name 动态获取子级下拉选项
       *
       * 可传，可不传（默认空）
       * */
      supName: {
        type: String,
        default: () => { return '' }
      },

      type: {
        type: String,
        default: () => { return '' }
      },

      /**
       * 编辑漏斗时需要传的参数，用于回填信息
       * 注意：编辑漏斗时，上面的 supName 字段必传
       * 默认值 { conditions: [], relation: '' }
       * */
      editArr: {
        type: Object,
        default: () => {
          return {
            conditions: [
              /*{ "field": "$distinct_id", "function": "equal", "params": ['a', 'b', 'c'] },
              { "field": "$time", "function": "absolute_between", "params": ["2021-06-01 00:00", "2021-06-09 00:00"] },
              { "field": "$element_position", "function": "notContain", "params": "100" },*/
            ],

            relation: 'or',       // 且 and | 或 or，conditions length 大于 1 时 relation 不可为空
          }
        }
      }
    },

    data() {
      return {
      	/* 唯一key*/
				listKey: 0,
        /* 当前选中item的下标 */
        currentItem: 0,

        /* 当前选中item的名字 如 $lib*/
        currentItemName: '',

        /* 一级下拉项 */
        levelOneOpts: [],

        /* 叶子节点的下拉选项 */
        lastOptsMap: [],

        /* data_type 为 bool 时选，没有 3 级信息 */
        boolOpts: DataTypeConfig.boolOpts,

        /* data_type 为 string 时选 */
        textOpts: DataTypeConfig.textOpts,

        /* data_type 为 number 时选 */
        numberOpts: DataTypeConfig.numberOpts,

        /* data_type 为 datetime 时选  */
        datetimeOpts: DataTypeConfig.datetimeOpts,

        /* data_type 为 list 时选 */
        listOpts: DataTypeConfig.listOpts,

        /* 且 and | 或 or */
        relation: { key: 'and', name: '且' },

        /* 日期选择器，不能选择今天以后的日期 */
        pickera_a_select_options: {
          disabledDate(time) {
            return time.getTime() > Date.now() - 8.64e6
          }
        },

        /* 相对事件发生时间 选项 */
        relativeEventTime: DataTypeConfig.relativeEventTime,

        /* 时间单位 选项 */
        timeUnit: DataTypeConfig.timeUnit,

        /* 自定义筛选 */
        arrSetting: [],

				/* 自定义筛选名字*/
				arrSettingName:[],

				/* 自定义筛选比较*/
				arrSettingCompare:[],

				/* 自定义筛选数值*/
				arrSettingValue:[],

				timeFlow:[
					{ val: 'after', label: '之后' },
					{ val: 'before', label: '之前' },
					{ val: 'curDay', label: '当天' },
					{ val: 'curWeek', label: '当周' },
					{ val: 'curMonth', label: '当月' }
				]
      }
    },
    created() {
			// eslint-disable-next-line @typescript-eslint/no-this-alias
      let t = this
      t.getFunnelCondition()
    },
    methods: {
			// 获取报表详情（存在chartId时）
			 getChartQueryData() {
				// eslint-disable-next-line @typescript-eslint/no-this-alias
				let t = this
				let chartId = this.$router.currentRoute.query.id
				if (chartId) {
					this.$request('/reportservice/chart', {
						method: 'GET',
						data: {
							projectId: Number(localStorage.getItem('productId')),
							chartId: Number(chartId)
						},
						customError: true
					})
						.then((res) => {
							let {code, data, message} = res
							if (code !== 200) {
								this.$message.error(message || message, 5)
								return
							}
							let {queryData} =data
							queryData = JSON.parse(queryData)

							let {filter} = queryData
							let {conditions} =filter
							if (conditions === undefined) {
								return
							}

							for (let i = 0; i < conditions.length; i++) {
								t.extracted(i, conditions)
							}
						})
						.catch((err) => {
							this.$message.error(err.msg || err.message, 5)
						})
				}
			},

			extracted(i,conditions) {
				// eslint-disable-next-line @typescript-eslint/no-this-alias
			 	let t = this
				for (let j = 0; j < t.levelOneOpts.length; j++) {
					if (t.levelOneOpts[j].attrCode === conditions[i].attr.attrCode) {
						t.editCond()
						t.arrSettingName[i] = t.levelOneOpts[j].attrName
						t.settingChange(i)

						t.arrSettingCompare[i] = conditions[i].functionCode
						t.changeSettingCompare(conditions[i].functionCode, i)

						if (conditions[i].params !== undefined) {
							t.arrSettingValue[i] = conditions[i].params
						}

						if (t.arrSettingCompare[i]==='absoluteBetween'){
							let params =[]

							params[0] = moment(conditions[i].params[0]).format()
							params[1] = moment(conditions[i].params[1]).format()
							t.arrSettingValue[i] = params
						}else{
							t.arrSettingValue[i] = conditions[i].params
						}
					}
				}
			},


			disabledDate(current){
				return current && current > moment().endOf('day')
			},
			changeData(e,item,index,i){
				this.$forceUpdate()
			},

			changeSettingCompare(item,index){
				if (item==="extractBetween"||item==="relativeCurTime"||item==="relativeBetween"){
					this.arrSettingValue[index]=["",""]
				}else if (item==="relativeEventTime"){
					this.arrSettingValue[index]=["","",""]
				}else if (item==="notRegexp"||item==="regexp"){
					this.arrSettingValue[index]=[""]
				}
				else{
					this.arrSettingValue[index]=[]
				}
			},
      /* 监听一级（主）筛选条件项 */
      settingChange(i) {
      	let listKey = this.arrSetting[i].listKey
				for (let j = 0; j <  this.levelOneOpts.length; j++) {
					if (this.levelOneOpts[j].attrName===this.arrSettingName[i]){
						this.arrSetting[i]=this.levelOneOpts[j]
					}
				}
				this.arrSetting[i]['listKey'] = listKey
				this.arrSettingCompare[i] = ""
				this.arrSettingValue[i] = []
				this.getCompareList(i)
        this.getValueList(i)

        this.$forceUpdate()  // 强制刷新组件数据
      },


      /* 切换【且】【或】 */
      switchRelation(val) {
        let valMap = {
          or: { key: 'or', name: '或' },
          and: { key: 'and', name: '且' },
        }

        if (val && valMap[val]) {
          this.relation = valMap[val]
          return
        }

        let key = this.relation.key
        this.relation = (key === 'and') ? { key: 'or', name: '或' } : { key: 'and', name: '且' }
      },

      /* 判断显示哪个三级选项 */
      showLeaf(i, str) {
        let obj = this.arrSetting[i]
        let dataType = obj['dataType']                 // 一级 type
        let newDataType = obj['new_data_type']         // 二级 type

        // 如果没有选择一级或二级，那么就隐藏三级
        if (!dataType || !newDataType || !newDataType.key) { return false }

        // 显示条件
        let objMap = DataTypeConfig.rules

        // 可自定义多个值，敲回车进行添加值 的组件
        if (objMap[str]) {
          let dataTypeArr = objMap[str].dataTypeArr
          let newDataTypeArr = objMap[str].newDataTypeArr

          return (dataTypeArr.indexOf(dataType) >= 0) && (newDataTypeArr.indexOf(newDataType.key) >= 0)
        }

        return false
      },

      /* 添加 add | 移除 remove 筛选条件 */
      editCond(i) {
        // 移除筛选条件
        if (typeof i === 'number') {
          this.arrSetting.splice(i, 1)
          this.lastOptsMap.splice(i, 1)
					this.arrSettingName.splice(i,1)
					this.arrSettingCompare.splice(i,1)
					this.arrSettingValue.splice(i,1)
          this.$forceUpdate()
          return
        }

        // 添加筛选项
				this.arrSetting.push({listKey: this.listKey})

				//给key索引加1
				this.listKey++

        // 默认【且】
        if (this.arrSetting.length === 2) {
          this.relation = { key: 'and', name: '且' }
        }


      },



			    /* 根据父级 data type 返回子级下拉选项 */
      getDataTypeOpts(i) {
        let dataType = this.arrSetting[i].dataType

        let objKey = {
          'string': 'textOpts',
          'number': 'numberOpts',
          'bool': 'boolOpts',
          'datetime': 'datetimeOpts',
          'list': 'listOpts',
        }
        if (objKey[dataType]) {return this[objKey[dataType]] }

        return []
      },

      /* 返回计算线条高度 */
      getLineHeight() {
        let len = this.arrSetting.length

        if (len < 2) { return 0 }
        if (len === 2) { return '38px' }
        return ((len - 2) * 38 + 38) + 'px'
      },

      getParams(item) {
        let objMap = DataTypeConfig.rules  //显示组件

        for (let key in objMap) {
          let obj = objMap[key]

          let arr1 = obj.dataTypeArr
          let arr2 = obj.newDataTypeArr
          if (arr1.indexOf(item.dataType) >= 0 && arr2.indexOf(item['new_data_type'].key) >= 0) {

            if (typeof obj.key === 'string') { return item[obj.key] }

            let arr3 = []
            for (let i = 0; i < obj.key.length; i++) {
              let k = obj.key[i]

              if (item[k].key) {
                arr3.push(item[k].key)
              } else {
                arr3.push(item[k])
              }
            }

            return arr3
          }
        }

        return false
      },

      /* 返回自定义筛选项 */
      getFilterConditions() {
        let arr = []
        let arrSetting = this.arrSetting

        if (!arrSetting || arrSetting.length === 0) { return {} }

        for (let i = 0; i < arrSetting.length; i++) {
        	let item ={}
					let attr = {}
					attr['attrCode'] = this.arrSetting[i].attrCode
					attr['attrName'] = this.arrSetting[i].attrName
					attr['attrType'] = 'user'
					attr['dataType'] = this.arrSetting[i].dataType
					attr['intervals'] = []

					item['attr'] = attr
					item['functionCode'] = this.arrSettingCompare[i]

					for (let j = 0; j < this.arrSetting[i].compareList; j++) {
						if (this.arrSettingCompare[i] === this.arrSetting[i].compareList[j].functionCode) {
							item['functionAlias'] = this.arrSettingCompare[i]
						}
					}
					if (this.arrSettingCompare[i]==='absoluteBetween'){
						let params =[]
						params[0] = Number(this.arrSettingValue[i][0])
						params[1] = Number(this.arrSettingValue[i][1])
						item['params'] = params
					}else{
						item['params'] = this.arrSettingValue[i]
					}

					arr.push(item)
        }

        if (arrSetting.length === 1) { return { conditions: arr } }

        return {
          conditions: arr,
          relation: this.relation.key,       // 且 | 或
        }
      },

      /* 获取一级下拉菜单选项（默认） */
      getFunnelCondition() {
				/*获取用户属性*/
				this.getUserAttr()
      },

			/*获取用户属性*/
			getUserAttr() {
				// eslint-disable-next-line @typescript-eslint/no-this-alias
				let t = this
				let param = {
					projectId: localStorage.getItem('productId')
				}
				// eslint-disable-next-line @typescript-eslint/no-unused-vars
				userAttrList(param).then((res) => {
					// 返回状态码如果不是 200，说明数据异常，需弹窗提示
					t.levelOneOpts = res.data
					t.getChartQueryData()
				}).catch((err) => {
					this.$message.error(err.msg || err.message, 5)
				})
			},

			/* 通过已选一级的值，获取二级下拉选项 */
			getCompareList(i) {
				// eslint-disable-next-line @typescript-eslint/no-this-alias
				let t = this
				let setting = t.arrSetting[i]
				let k = setting.dataType
				let param ={
					dataType:k
				}
				if (k === undefined) {
					return
				}
				compareList(param).then((res)=>{
					t.arrSetting[i].compareList = res.data
					this.$forceUpdate()
				}).catch((err) => {
					this.$message.error(err.msg || err.message, 5)
				})
			},
      /* 通过已选一级的值，获取三级下拉选项 */
      getValueList(i) {
				// eslint-disable-next-line @typescript-eslint/no-this-alias
        let t = this
        let setting = t.arrSetting[i]
        let k = setting.attrCode

        let param = {
					projectId: localStorage.getItem('productId'),
					attrType: "user",
					attrCode: t.arrSetting[i].attrCode,
					keywords: "",
					size: 30
        }

        valueList(param).then((res) => {
          t.arrSetting[i].valueList = res.data
          t.$forceUpdate()  // 强制刷新组件数据
        }).catch((error) => {
              t.lastOptsMap[i][k] = []
              console.log('error = ', error)
        })
      },

      isArray(a) {
        return (Object.prototype.toString.call(a) === '[object Array]')
      },

      /* 数组去重 */
      MergeArray(arr1, arr2) {
        let _arr = []

        for (let i = 0; i < arr1.length; i++) { _arr.push(arr1[i]) }

        for (let i = 0; i < arr2.length; i++) {
          let flag = true

          for (let j = 0; j < arr1.length; j++) {
            if (arr2[i] == arr1[j]) {
              flag = false
              break
            }
          }

          if (flag) { _arr.push(arr2[i]) }
        }

        return _arr
      },

    },
    watch: {
      'arrSetting.length':{
        handler: function (val,oldval)
        {
          if (val !== 0) {
            if (this.lastOptsMap[val-1] === undefined) {
              this.lastOptsMap.push([])
            }
          }
        },
        deep: true
      },
    },
  }
</script>



<style scoped lang="scss">
  .viewFunnelBox {
    padding: 10px 0;
    position: relative;

    .title-size {
      display: inline-block;
      width: 80px;
      padding: 0 10px;
      text-align: right;
    }

    .a-select { margin-right: 10px; }
  }

	.a-select-width{
		width: 100px;
	}
  .funnelSettingBox {
		border-left: 1px solid #17B9E6;
    padding: 5px 0 5px 17px;
    position: relative;

    &:hover { background-color: #fafafa; }

    input[type='number'] { padding-right: 0; }

    .a-select {margin-right: 10px;}

    .size { padding-right: 5px;}

    .betweenBox,
    .datetimeBox { display: inline-block; }
  }

  i.el-icon-delete {
    position: absolute;
    right: 20px;
    top: 50%;
    transform: translate(0, -50%);
    cursor: pointer;

    &:hover { color: rgb(247, 86, 94); }
  }

  /* 且或非 */
  .andOrNotBox-and {
		position: absolute;
		top: 50%;
    width: 18px;
    height: 25px;
    font-size: 12px;
    text-align: center;
    line-height: 25px;
    background-color: #40a9ff;
    cursor: pointer;
    z-index: 10;
    transform: translate(46px, -100%);
		margin-left: -53px;
  }

	.andOrNotBox-or {
		position: absolute;
		top: 50%;
		width: 18px;
		height: 25px;
		font-size: 12px;
		text-align: center;
		line-height: 25px;
		background-color: #ffffff;
		cursor: pointer;
		z-index: 10;
		transform: translate(46px, 0%);
		margin-left: -53px;
	}

  .lineBox {
    width: 26px;
    border: 1px solid #cccccc;
    border-right: none;
    transform: translate(60px, -50%);
    z-index: 5;
  }
</style>
